LeetCode Algorithms 2 两数相加

1. 题目描述

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

1
2
3
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

2. 题解

2.1. 思路

竖式加法。左边是低位,右边是高位

1
2
3
4
    (2 -> 4 -> 3) 
+ (5 -> 6 -> 4)
-----------------
= (7 -> 0 -> 8)

假设m和n分别代表两个链表的长度

时间复杂度:O(max{m, n}),因为长的链表遍历完就结束

空间复杂度:O(max{m, n}),因为新链表长度取决于长链表

2.2. Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for singly-linked list.
* public class ListNode {
* long val;
* ListNode next;
* ListNode(long x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p = l1;
ListNode q = l2;
ListNode list = new ListNode(-1);
ListNode tail = list;
int sumWithCarry = 0;
while (p != null || q != null) {
if (p != null) {
sumWithCarry += p.val;
p = p.next;
}
if (q != null) {
sumWithCarry += q.val;
q = q.next;
}
tail.next = new ListNode(sumWithCarry % 10);
tail = tail.next;
sumWithCarry /= 10;
}
// 如果有多余的进位,则再添加1个节点
if (sumWithCarry > 0) {
tail.next = new ListNode(sumWithCarry);
tail = tail.next;
}
return list.next;
}
}
panchaoxin wechat
关注我的公众号
支持一下